package edu.uci.hm.events;

import java.io.*;

import edu.uci.hm.util.Util;

public final class EventsReader {
	private RandomAccessFile eventsFile;
	private static final int BUF_SIZE = 150000 * 32;
	public final static int EVENT_SIZE = 32;
	private byte[] buf;
	private int offset;
	private int loadedSize;

	public EventsReader(String folderName, String fileName) {
		try {
			eventsFile = new RandomAccessFile(folderName + "/" + fileName, "rw");
			eventsFile.seek(0);
			buf = new byte[BUF_SIZE];
			offset = 0;
			loadedSize = 0;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void seekOffset(long offset) {
		try {
			eventsFile.seek(offset);
			this.offset = 0;
			loadedSize = 0;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void close() {
		try {
			eventsFile.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void reset() {
		try {
			eventsFile.seek(0);
			offset = 0;
			loadedSize = 0;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Event getNext() {
		try {
			if (offset + 32 > loadedSize) {
				loadedSize = eventsFile.read(buf, 0, BUF_SIZE);
				if (loadedSize < 0) {
					return null;
				}
				offset = 0;
			}
			Event event = new Event();
			event.s_uid = Util.toLong(buf, offset);
			event.size = Util.toInt(buf, offset + 8);
			event.o_uid = Util.toLong(buf, offset + 12);
			event.rev_ordinal = Util.toInt(buf, offset + 20);
			event.page_id = Util.toInt(buf, offset + 24);
			event.ts = Util.toInt(buf, offset + 28);

			offset += 32;
			return event;
		} catch (IOException e) {
		}
		return null;
	}

	public static void main(String[] args) {
		EventsReader reader = new EventsReader("foldername",
				"vd2-events");
		Event event;
		int i = 0;
		while ((event = reader.getNext()) != null) {
			i++;
			if (i % 2000000 == 0) {
				break;
			}
			System.out.println(event.s_uid + "," + event.size + ","
					+ event.o_uid + "," + event.rev_ordinal + ","
					+ event.page_id + "," + event.ts);
		}
	}
}
